﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using UnionistsManagement_DaLat.Areas.Admin.CustomMemberShip;
using UnionistsManagement_DaLat.Areas.Admin.Models;

namespace UnionistsManagement_DaLat.Areas.Admin.Controllers
{
    public class Ad_AccountController : Controller
    {
        private UnionistsManagementContext db = new UnionistsManagementContext();
        private CustomMemberShipProvider customMemberShip = new CustomMemberShipProvider();
        // GET: /Admin/Account/
        public ActionResult Index()
        {
            var accounts = db.Accounts.Include(a => a.Unionist);
            return View(accounts.ToList());
        }

        // GET: /Admin/Account/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Account account = db.Accounts.Find(id);
            if (account == null)
            {
                return HttpNotFound();
            }
            return View(account);
        }

        // GET: /Admin/Account/Create
        public ActionResult Create()
        {
            ViewBag.ID = new SelectList(db.Unionists, "ID", "StudentCode");
            return View();
        }

        // POST: /Admin/Account/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Username,Password,FullName,Email,LastLogin,IsLock,IsEnable")] Account account)
        {
            if (ModelState.IsValid)
            {
                db.Accounts.Add(account);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ID = new SelectList(db.Unionists, "ID", "StudentCode", account.ID);
            return View(account);
        }

        // GET: /Admin/Account/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Account account = db.Accounts.Find(id);
            if (account == null)
            {
                return HttpNotFound();
            }
            ViewBag.ID = new SelectList(db.Unionists, "ID", "StudentCode", account.ID);
            return View(account);
        }

        // POST: /Admin/Account/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Username,Password,FullName,Email,LastLogin,IsLock,IsEnable")] Account account)
        {
            if (ModelState.IsValid)
            {
                db.Entry(account).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ID = new SelectList(db.Unionists, "ID", "StudentCode", account.ID);
            return View(account);
        }

        // GET: /Admin/Account/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Account account = db.Accounts.Find(id);
            if (account == null)
            {
                return HttpNotFound();
            }
            return View(account);
        }

        // POST: /Admin/Account/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Account account = db.Accounts.Find(id);
            db.Accounts.Remove(account);
            db.SaveChanges();
            return RedirectToAction("Index");
        }


        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (customMemberShip.ValidateUser(model.Username, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", "Tài khoản hoặc mật khẩu không tồn tại, vui lòng kiểm tra lại");
                }
            }
            return View(model);
        }


        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
        }

        /// <summary>
        /// Phân quyền
        /// </summary>
        /// <returns></returns>
        public ActionResult RoleManagement()
        {
            var listRoles = db.Roles.ToList();
            ViewBag.Roles = listRoles;
            return View(listRoles);
        }

        [HttpPost]
        public ActionResult RoleManagement(int roleId, int[] functionChecked)
        {
           
            if (functionChecked != null && functionChecked.Length > 0 && roleId != null)
            {
                var access = db.Accesses.Where(a => a.Role.ID == roleId).ToList();
               access.ForEach(a =>
               {
                   db.Accesses.Remove(a);
                   db.SaveChanges();
               });
                foreach (var i in functionChecked)
                {
                    var func = db.Functions.FirstOrDefault(f => f.ID == i);
                    var role = db.Roles.FirstOrDefault(r => r.ID == roleId);
                   
                    if (func != null && role != null)
                    {
                      
                        db.Accesses.Add(new Access()
                           {
                               Function = func,
                               Role = role
                           });
                        db.SaveChanges();


                    }
                }
                ViewBag.Messenger = "Thành công mỹ mãn";
            }
            else
            {
                db.Accesses.RemoveRange(db.Accesses.Where(a => a.Role.ID == roleId).ToList());
                db.SaveChanges();
                ViewBag.Messenger = "Thành công mỹ mãn";
            }
            return RedirectToAction("RoleManagement");
        }


        public PartialViewResult GetListFunctionByRole(string roleID)
        {
            var listFunction = db.FunctionCatalogs.ToList();
            ViewBag.FunctionCatalogs = listFunction;
            var id = int.Parse(roleID);
            var listFunc = db.Accesses.Where(a => a.Role.ID == id).ToList();
            ViewBag.ListFunc = listFunc;
            return PartialView("_ListFunction");
        }

        [HttpPost]
        public string a()
        {
            return "a";
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
